import React from 'react';
import Markdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import remarkMath from 'remark-math';
import rehypeKatex from 'rehype-katex';
import rehypeHighlight from 'rehype-highlight';
import remarkBreaks from 'remark-breaks';
import 'katex/dist/katex.min.css'; // 引入 KaTeX 样式
// import 'highlight.js/styles/tokyo-night-dark.min.css'; // 引入代码高亮样式
import 'highlight.js/styles/atom-one-dark.min.css'; // 引入代码高亮样式

// import '@/assets/atom-one-dark.css'

function escapeBrackets(text) {
  const pattern =
    /(```[\s\S]*?```|`.*?`)|\\\[([\s\S]*?[^\\])\\\]|\\\((.*?)\\\)/g;
  return text.replace(
    pattern,
    (match, codeBlock, squareBracket, roundBracket) => {
      if (codeBlock) {
        return codeBlock;
      } else if (squareBracket) {
        return `$$${squareBracket}$$`;
      } else if (roundBracket) {
        return `$${roundBracket}$`;
      }
      return match;
    },
  );
}


const MarkdownRenderer = ({ content }) => {
  let markdown_content = escapeBrackets(content);

  return <Markdown

    children={markdown_content}

    remarkPlugins={[remarkGfm, remarkMath, remarkBreaks]}

    rehypePlugins={[ rehypeKatex, rehypeHighlight]}

    components={{
      // 自定义代码块的渲染
      code({ node, inline, className, children, ...props }) {
        const match = /language-(\w+)/.exec(className || '');
        return !inline && match ? (
          <pre className={className}>
            <code className={className} {...props}>
              {children}
            </code>
          </pre>
        ) : (
          <code className={className} {...props}>
            {children}
          </code>
        );
      }
    }}
  />;
};

export default MarkdownRenderer